﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataTier.Entities;

namespace DataTier.Helpers
{
    /// <summary>
    /// Хэлпер для работы с пользовательскими бизнес-объектами
    /// </summary>
    public static class EntityHelper
    {
        #region Блок методов для Заказов

        /// <summary>
        /// Возвращает EntityFramework-объект Order по пользовательскому классу OrderEntity
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Order GetOrder(OrderEntity entity)
        {
            if (entity.Header == null)
                return null;

            Order order = entity.Header;
            if (entity.Specification != null && entity.Specification.Count > 0)
            {
                order.OrderSpec = new System.Data.Objects.DataClasses.EntityCollection<OrderSpec>();
                foreach (var spec in entity.Specification)
                {
                    if (order.Id > 0)
                        spec.Specification.OrderId = order.Id;

                    order.OrderSpec.Add(spec.Specification);
                    // Неясно пока надо ли тут обрабатывать объект spec.Product ???
                }
            }
            return order;
        }


        /// <summary>
        /// Возвращает пользовательский класс OrderEntity по EntityFramework-объекту Order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static OrderEntity GetOrderEntity(Order order)
        {
            if (order == null)
                return null;

            OrderEntity entity = new OrderEntity();
            entity.Header = order;
            if (order.OrderSpec != null && order.OrderSpec.Count > 0)
                entity.Specification = order.OrderSpec.Select(s => EntityHelper.GetOrderSpecEntity(s)).ToList();
            
            if (order.State != null)
                entity.State = order.State;

            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс OrderSpecEntity по EntityFramework-объекту OrderSpec
        /// </summary>
        /// <param name="spec"></param>
        /// <returns></returns>
        public static OrderSpecEntity GetOrderSpecEntity(OrderSpec spec)
        {
            if (spec == null)
                return null;

            OrderSpecEntity entity = new OrderSpecEntity();
            entity.Specification = spec;
            //entity.Product = spec.Product;

            return entity;
        }


        /// <summary>
        /// Возвращает список пользовательских классов OrderEntity по списку EntityFramework-объектов Order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static List<OrderEntity> GetOrderEntityList(List<Order> orders)
        {
            if (orders == null || orders.Count == 0)
                return null;

            List<OrderEntity> entities = new List<OrderEntity>();
            foreach (var order in orders)
            {
                var o = EntityHelper.GetOrderEntity(order);
                if (o != null)
                    entities.Add(o);
            }

            return entities;
        }


        /// <summary>
        /// Возвращает список пользовательских классов OrderFullInfoEntity по списку EntityFramework-объектов Order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static List<OrderFullInfoEntity> GetOrderFullInfoEntityList(List<Order> orders)
        {
            if (orders == null || orders.Count == 0)
                return null;

            List<OrderFullInfoEntity> entities = new List<OrderFullInfoEntity>();
            foreach (var order in orders)
            {
                var o = EntityHelper.GetOrderFullInfoEntity(order);
                if (o != null)
                    entities.Add(o);
            }

            return entities;
        }


        /// <summary>
        /// Возвращает пользовательский класс OrderFullInfoEntity по EntityFramework-объекту Order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static OrderFullInfoEntity GetOrderFullInfoEntity(Order order)
        {
            if (order == null)
                return null;

            OrderFullInfoEntity entity = new OrderFullInfoEntity();
            entity.IsModifiedByAdmin = order.IsModifiedByAdmin;
            entity.Id = order.Id;
            entity.Number = order.Number;
            entity.CreatedUserId = order.CreatedUserId;
            entity.CreatedUserName = (order.User != null) ? order.User.FIO : "";
            entity.CreatedDate = order.CreatedDate;
            entity.ModifiedUserId = order.ModifiedUserId;
            entity.ModifiedUserName = (order.User1 != null) ? order.User1.FIO : "";
            entity.ModifiedDate = order.ModifiedDate;
            entity.ItogoSumm = order.ItogoSumm;
            entity.StateId = order.StateId;
            entity.StateName = (order.State != null) ? order.State.Name : "";
            entity.StateColor = (order.State != null) ? order.State.Color : "";
            entity.StateDescription = (order.State != null) ? order.State.Description : "";

            entity.AccountNumber = order.AccNumber;
            if (order.User2 != null)
            {   
                entity.AccountCreatedUserId = order.AccCreatedUserId;
                entity.AccountCreatedUserName = order.User2.FIO;
                entity.AccountCreatedDate = order.AccCreatedDate;
            }
            
            if (order.StateId == (int)StateEnum.FullDispatch)
                entity.AccountStateName = "Полностью отгружен";
            else if (order.StateId == (int)StateEnum.PartialDispatch)
                entity.AccountStateName = "Частично отгружен";

            entity.ExistsIsUnavailable = false;
            //foreach (var p in order.OrderSpec.Select(o => o.Product))
            //{
            //    if (p.IsUnavailable.HasValue && p.IsUnavailable == true)
            //    {
            //        entity.ExistsIsUnavailable = true;
            //        break;
            //    }
            //}
            foreach (var p in order.OrderSpec)
            {
                if (p.IsUnavailable.HasValue && p.IsUnavailable == true)
                {
                    entity.ExistsIsUnavailable = true;
                    break;
                }
            }


            if (order.User != null && order.User.CostsCenter != null)
            {
                entity.CreatedCostCenterId = order.User.CostsCenter.CostsCenterId;
                entity.CreatedCostCenterName = order.User.CostsCenter.Name;

                if (order.User.CostsCenter.Department != null)
                {
                    entity.CreatedDepartmentId = order.User.CostsCenter.Department.DepartmentId;
                    entity.CreatedDepartmentName = order.User.CostsCenter.Department.Name;
                    entity.CreatedDepartmentOfficeNumber = order.User.CostsCenter.Department.OfficeNumber;

                    if (order.User.CostsCenter.Department.JuridicalPerson != null)
                    {
                        entity.CreatedJuridicalPersonId = order.User.CostsCenter.Department.JuridicalPerson.JuridicalPersonId;
                        entity.CreatedJuridicalPersonName = order.User.CostsCenter.Department.JuridicalPerson.Name;

                        if (order.User.CostsCenter.Department.JuridicalPerson.Company != null)
                        {
                            entity.CreatedCompanyId = order.User.CostsCenter.Department.JuridicalPerson.Company.CompanyId;
                            entity.CreatedCompanyName = order.User.CostsCenter.Department.JuridicalPerson.Company.CompanyName;
                            entity.CreatedCompanyAddress = order.User.CostsCenter.Department.JuridicalPerson.Company.Address;
                        }
                    }
                }
            }

            return entity;
        }

        #endregion Блок методов для Заказов


        #region Блок методов для прав доступа

        /// <summary>
        /// Возвращает пользовательский класс UserSecurityDetails с полной информацией о пользователе и его правах доступа
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static UserSecurityDetails GetUserSecurityDetails(User user)
        {
            if (user == null)
                return null;

            UserSecurityDetails entity = new UserSecurityDetails();
            entity.User = user;

            //Информация о вхождении пользователя в центр застрат, отдел, департамент, юр.лицо, компанию
            if (user.CostsCenter != null)
            {
                entity.CostsCenter = user.CostsCenter;
                if (user.CostsCenter.Department != null)
                {
                    entity.Department = user.CostsCenter.Department;
                    if (user.CostsCenter.Department.JuridicalPerson != null)
                    {
                        entity.JuridicalPerson = user.CostsCenter.Department.JuridicalPerson;
                        if (user.CostsCenter.Department.JuridicalPerson.Company != null)
                            entity.Company = user.CostsCenter.Department.JuridicalPerson.Company;
                    }
                }
            }

            //Информация о роли и правах пользователя
            if (user.Role != null)
            {
                entity.Role = EntityHelper.GetRoleEntity(user.Role);
            }


            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс RoleEntity с полной информацией о РОЛИ пользователя
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public static RoleEntity GetRoleEntity(Role role)
        {
            if (role == null)
                return null;

            RoleEntity entity = new RoleEntity();
            entity.Role = role;

            if (role.Permission != null && role.Permission.Count > 0)
            {
                entity.Permissions = role.Permission.Select(p => EntityHelper.GetPermissionEntity(p)).ToList();
            }

            // Выбираем список разрешенных пунктов меню
            var menus = role.Permission.Where(p => p.Menu != null && p.Menu.Count > 0).Select(p => p.Menu).FirstOrDefault();
            if (menus != null && menus.Count > 0)
                entity.Menus = menus.ToList();

            // Выбираем список разрешенных для работы статусов (разрешения для перевода в этот статус)
            var states = role.Permission.Where(p => p.State != null && p.State.Count > 0).Select(p => p.State).FirstOrDefault();
            if (states != null && states.Count > 0)
                entity.States = states.ToList();


            // Выбираем список разрешенных web-страниц
            var webPages = role.Permission.Where(p => p.WebPage != null && p.WebPage.Count > 0 && (p.State == null || p.State.Count == 0)).Select(p => p.WebPage).FirstOrDefault();
            if (webPages != null && webPages.Count > 0)
                entity.WebPages = webPages.ToList();
            
            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс RoleEntity с полной информацией о ПРАВАХ конкретной РОЛИ пользователя
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        public static PermissionEntity GetPermissionEntity(Permission permission)
        {
            if (permission == null)
                return null;

            PermissionEntity entity = new PermissionEntity();
            entity.Permission = permission;
            entity.PermissionCategory = permission.PermissionCategory;

            return entity;
        }

        #endregion Блок методов для прав доступа


        #region Блок методов для Расходных накладных

        /// <summary>
        /// Возвращает пользовательский класс ExpendBillEntity по EntityFramework-объекту ExpendBill
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static ExpendBillEntity GetExpendBillEntity(ExpendBill expendBill)
        {
            if (expendBill == null)
                return null;

            ExpendBillEntity entity = new ExpendBillEntity();
            entity.ExpendBill = expendBill;
            entity.ExpendBillId = expendBill.Id;

            if (expendBill.Order != null)
            {
                entity.Order = EntityHelper.GetOrderEntity(expendBill.Order);
                //entity.OrderId = expendBill.OrderId;
                entity.OrderId = expendBill.Order.Id;

                entity.OrderFullInfo = EntityHelper.GetOrderFullInfoEntity(expendBill.Order);
            }

            if (expendBill.State != null)
                entity.State = expendBill.State;

            if (expendBill.ExpendBillSpec != null && expendBill.ExpendBillSpec.Count > 0)
                //entity.Specification = expendBill.ExpendBillSpec.Select(s => EntityHelper.GetExpendBillSpecEntity(s)).ToList();
                entity.Specification = expendBill.ExpendBillSpec.ToList();

            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс ExpendBillSpecEntity по EntityFramework-объекту ExpendBillSpec
        /// </summary>
        /// <param name="spec"></param>
        /// <returns></returns>
        public static ExpendBillSpecEntity GetExpendBillSpecEntity(ExpendBillSpec spec)
        {
            if (spec == null)
                return null;

            ExpendBillSpecEntity entity = new ExpendBillSpecEntity();
            entity.Specification = spec;
            //entity.Product = spec.Product;

            return entity;
        }


        /// <summary>
        /// Возвращает EntityFramework-объект ExpendBill по пользовательскому классу ExpendBillEntity 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ExpendBill GetExpendBill(ExpendBillEntity entity)
        {
            if (entity == null)
                return null;

            ExpendBill expendBill = new ExpendBill()
            {
                Id = entity.ExpendBill.Id,
                CreatedDate = entity.ExpendBill.CreatedDate,
                CreatedUserId = entity.ExpendBill.CreatedUserId,
                ItogoSumm = entity.ExpendBill.ItogoSumm,
                Number = entity.ExpendBill.Number,
                NumberTotal = entity.ExpendBill.NumberTotal,
                OrderId = entity.ExpendBill.OrderId,
                StateId = entity.ExpendBill.StateId,
                ExpendBillDate = entity.ExpendBill.ExpendBillDate
            };
            //expendBill.Order = EntityHelper.GetOrder(entity.Order);

            if (entity.Specification != null)
            {
                expendBill.ExpendBillSpec = new System.Data.Objects.DataClasses.EntityCollection<ExpendBillSpec>();
                foreach (var item in entity.Specification)
                {
                    //expendBill.ExpendBillSpec.Add(EntityHelper.GetExpendBillSpec(item));
                    expendBill.ExpendBillSpec.Add(item);
                }
            }

            return expendBill;
        }


        /// <summary>
        /// Возвращает EntityFramework-объект ExpendBillSpec по пользовательскому классу ExpendBillSpecEntity 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ExpendBillSpec GetExpendBillSpec(ExpendBillSpecEntity entity)
        {
            if (entity == null)
                return null;

            ExpendBillSpec spec = new ExpendBillSpec()
            {
                Count = entity.Specification.Count,
                ProductId = entity.Specification.ProductId,
                Artikul = entity.Specification.Artikul,
                ProductName = entity.Specification.ProductName,
                Price = entity.Specification.Price,
                IsUnavailable = entity.Specification.IsUnavailable,
                SupplierName = entity.Specification.SupplierName,
                SupplierArtikul = entity.Specification.SupplierArtikul,
                Summa = entity.Specification.Summa,
                ExpendBillId = entity.Specification.ExpendBillId,
                RowId = entity.Specification.RowId
            };
            //spec.Product = entity.Product; // Под вопросом, надо ли.

            return spec;
        }



        #endregion Блок методов для Расходных накладных


        #region Блок методов для Консолидированных счетов

        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountEntity по EntityFramework-объекту ConsolidatedAccount 
        /// </summary>
        /// <param name="consolidatedAccount"></param>
        /// <returns></returns>
        public static ConsolidatedAccountEntity GetConsolidatedAccountEntity(ConsolidatedAccount consolidatedAccount)
        {
            if (consolidatedAccount == null)
                return null;

            ConsolidatedAccountEntity entity = new ConsolidatedAccountEntity();
            entity.ConsolidatedAccount = consolidatedAccount;
            entity.Id = consolidatedAccount.Id;
            entity.JuridicalPerson = consolidatedAccount.JuridicalPerson;

            if (consolidatedAccount.ExpendBill != null && consolidatedAccount.ExpendBill.Count > 0)
                entity.ExpendBillIds = consolidatedAccount.ExpendBill.Select(b => b.Id).ToList();

            if (consolidatedAccount.State != null)
                entity.State = consolidatedAccount.State;

            if (consolidatedAccount.ConsolidatedAccountSpec != null && consolidatedAccount.ConsolidatedAccountSpec.Count > 0)
                //entity.Specification = consolidatedAccount.ConsolidatedAccountSpec.Select(s => EntityHelper.GetConsolidatedAccountSpecEntity(s)).ToList();
                entity.Specification = consolidatedAccount.ConsolidatedAccountSpec.ToList();

            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountSpecEntity по EntityFramework-объекту ConsolidatedAccountSpec
        /// </summary>
        /// <param name="spec"></param>
        /// <returns></returns>
        public static ConsolidatedAccountSpecEntity GetConsolidatedAccountSpecEntity(ConsolidatedAccountSpec spec)
        {
            if (spec == null)
                return null;

            ConsolidatedAccountSpecEntity entity = new ConsolidatedAccountSpecEntity();
            entity.Specification = spec;
            //entity.Product = spec.Product;

            return entity;
        }


        /// <summary>
        /// Возвращает EntityFramework-объект ConsolidatedAccount по пользовательскому классу ConsolidatedAccountEntity 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ConsolidatedAccount GetConsolidatedAccount(ConsolidatedAccountEntity entity)
        {
            if (entity == null)
                return null;

            ConsolidatedAccount consolidatedAccount = new ConsolidatedAccount()
            {
                JuridicalPersonId = entity.ConsolidatedAccount.JuridicalPersonId,
                PeriodDateEnd = entity.ConsolidatedAccount.PeriodDateEnd,
                PeriodDateStart = entity.ConsolidatedAccount.PeriodDateStart,
                Id = entity.ConsolidatedAccount.Id,
                CreatedDate = entity.ConsolidatedAccount.CreatedDate,
                CreatedUserId = entity.ConsolidatedAccount.CreatedUserId,
                Number = entity.ConsolidatedAccount.Number,
                StateId = entity.ConsolidatedAccount.StateId
            };

            if (entity.Specification != null)
            {
                consolidatedAccount.ConsolidatedAccountSpec = new System.Data.Objects.DataClasses.EntityCollection<ConsolidatedAccountSpec>();
                foreach (var item in entity.Specification)
                {
                    consolidatedAccount.ConsolidatedAccountSpec.Add(item);
                }
            }

            return consolidatedAccount;
        }
        
        #endregion Блок методов для Консолидированных счетов




        #region Блок методов для Консолидированных счетов 2

        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountEntity по EntityFramework-объекту ConsolidatedAccount 
        /// </summary>
        /// <param name="consolidatedAccount"></param>
        /// <returns></returns>
        public static CAEntity2 GetConsolidatedAccountEntity2(ConsolidatedAccount consolidatedAccount)
        {
            if (consolidatedAccount == null)
                return null;

            CAEntity2 entity = new CAEntity2()
            {
                Id = consolidatedAccount.Id,
                CreatedDate = consolidatedAccount.CreatedDate,
                CreatedUserId = consolidatedAccount.CreatedUserId,
                Number = consolidatedAccount.Number,
                JuridicalPersonId = consolidatedAccount.JuridicalPersonId,
                PeriodDateStart = consolidatedAccount.PeriodDateStart,
                PeriodDateEnd = consolidatedAccount.PeriodDateEnd,
                StateId = consolidatedAccount.StateId
            };

            entity.JuridicalPerson = consolidatedAccount.JuridicalPerson;

            if (consolidatedAccount.ExpendBill != null && consolidatedAccount.ExpendBill.Count > 0)
                entity.ExpendBillIds = consolidatedAccount.ExpendBill.Select(b => b.Id).ToList();

            if (consolidatedAccount.State != null)
                entity.State = consolidatedAccount.State;

            if (consolidatedAccount.ConsolidatedAccountSpec != null && consolidatedAccount.ConsolidatedAccountSpec.Count > 0)
                entity.Specification = consolidatedAccount.ConsolidatedAccountSpec.Select(s => EntityHelper.GetConsolidatedAccountSpecEntity2(s)).ToList();

            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountSpecEntity по EntityFramework-объекту ConsolidatedAccountSpec
        /// </summary>
        /// <param name="spec"></param>
        /// <returns></returns>
        public static CASEntity2 GetConsolidatedAccountSpecEntity2(ConsolidatedAccountSpec spec)
        {
            if (spec == null)
                return null;

            CASEntity2 entity = new CASEntity2()
            {
                CAId = spec.ConsolidatedAccountId,
                RowId = spec.RowId,
                ProductId = spec.ProductId,
                Artikul = spec.Artikul,
                ProductName = spec.ProductName,
                Price = spec.Price,
                IsUnavailable = spec.IsUnavailable,
                SupplierName = spec.SupplierName,
                SupplierArtikul = spec.SupplierArtikul,
                Count = spec.Count,
                Summa = spec.Summa
            };

            return entity;
        }


        /// <summary>
        /// Возвращает EntityFramework-объект ConsolidatedAccount по пользовательскому классу ConsolidatedAccountEntity 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ConsolidatedAccount GetConsolidatedAccount2(CAEntity2 entity)
        {
            if (entity == null)
                return null;

            ConsolidatedAccount consolidatedAccount = new ConsolidatedAccount()
            {
                JuridicalPersonId = entity.JuridicalPersonId,
                PeriodDateEnd = entity.PeriodDateEnd,
                PeriodDateStart = entity.PeriodDateStart,
                Id = entity.Id,
                CreatedDate = entity.CreatedDate,
                CreatedUserId = entity.CreatedUserId,
                Number = entity.Number,
                StateId = entity.StateId
            };

            if (entity.Specification != null)
            {
                consolidatedAccount.ConsolidatedAccountSpec = new System.Data.Objects.DataClasses.EntityCollection<ConsolidatedAccountSpec>();
                foreach (var item in entity.Specification)
                    consolidatedAccount.ConsolidatedAccountSpec.Add(EntityHelper.GetConsolidatedAccountSpec2(item));
            }

            return consolidatedAccount;
        }


        /// <summary>
        /// Возвращает EntityFramework-объект ConsolidatedAccountSpec по пользовательскому классу ConsolidatedAccountSpecEntity2
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ConsolidatedAccountSpec GetConsolidatedAccountSpec2(CASEntity2 entity)
        {
            if (entity == null)
                return null;

            ConsolidatedAccountSpec consolidatedAccountSpec = new ConsolidatedAccountSpec()
            {
                ConsolidatedAccountId = entity.CAId,
                RowId = entity.RowId,
                ProductId = entity.ProductId,
                Artikul = entity.Artikul,
                ProductName = entity.ProductName,
                Price = entity.Price,
                IsUnavailable = entity.IsUnavailable,
                SupplierName = entity.SupplierName,
                SupplierArtikul = entity.SupplierArtikul,
                Count = entity.Count,
                Summa = entity.Summa
            };

            return consolidatedAccountSpec;
        }

        #endregion Блок методов для Консолидированных счетов 2

        
        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountOtgruzkaEntity по EntityFramework-объекту ConsolidatedAccount 
        /// </summary>
        /// <param name="consolidatedAccount"></param>
        /// <returns></returns>
        public static ConsolidatedAccountOtgruzkaEntity GetConsolidatedAccountOtgruzkaEntity(ConsolidatedAccount consolidatedAccount)
        {
            if (consolidatedAccount == null)
                return null;

            ConsolidatedAccountOtgruzkaEntity entity = new ConsolidatedAccountOtgruzkaEntity()
            {
                Id = consolidatedAccount.Id,
                CreatedDate = consolidatedAccount.CreatedDate,
                CreatedUserId = consolidatedAccount.CreatedUserId,
                Number = consolidatedAccount.Number,
                JuridicalPersonId = consolidatedAccount.JuridicalPersonId,
                PeriodDateStart = consolidatedAccount.PeriodDateStart,
                PeriodDateEnd = consolidatedAccount.PeriodDateEnd,
                StateId = consolidatedAccount.StateId
            };

            entity.JuridicalPerson = consolidatedAccount.JuridicalPerson;

            if (consolidatedAccount.ExpendBill != null && consolidatedAccount.ExpendBill.Count > 0)
            {
                entity.OrderOtgruzkaList = new List<OrderOtgruzkaEntity>();

                foreach (var bill in consolidatedAccount.ExpendBill)
                {
                    if (bill.StateId == (int)StateEnum.ExpendBillExecuted)
                    {
                        var otgruzka = entity.OrderOtgruzkaList.Where(o => o.CostsCenterId == bill.Order.User.CostsCenterId).FirstOrDefault();
                        if (otgruzka != null) // Увеличиваем сумму и прибавляем рассматриваемый заказ в список заказов
                        {
                            otgruzka.Summa += Math.Round(bill.ExpendBillSpec.Sum(s => Math.Round(s.Summa, 2)), 2); //otgruzka.Summa += bill.ItogoSumm;
                            if (otgruzka.Orders == null)
                                otgruzka.Orders = new List<OrderFullInfoEntity>();
                            if (!otgruzka.Orders.Where(o => o.Id == bill.OrderId).Any())
                                otgruzka.Orders.Add(EntityHelper.GetOrderFullInfoEntity(bill.Order));
                        }
                        else // создаем запись для конкретный центр затрат
                        {
                            var item = new OrderOtgruzkaEntity();
                            item.Summa += Math.Round(bill.ExpendBillSpec.Sum(s => Math.Round(s.Summa, 2)), 2); //item.Summa = bill.ItogoSumm;
                            item.CostsCenterId = bill.Order.User.CostsCenterId;
                            //item.CostsCenterName = bill.Order.User.CostsCenter.Department.Name + " / " + bill.Order.User.CostsCenter.Name;
                            item.CostsCenterName = bill.Order.User.CostsCenter.BS + " / " + bill.Order.User.CostsCenter.MVZ;
                            item.Orders = new List<OrderFullInfoEntity>() { EntityHelper.GetOrderFullInfoEntity(bill.Order) };
                            entity.OrderOtgruzkaList.Add(item);
                        }
                    }
                }


                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var summm0 = consolidatedAccount.ConsolidatedAccountSpec.Sum(c => c.Summa);
                System.Diagnostics.Debug.WriteLine(string.Format("summm0={0}", summm0));
                var summm1 = consolidatedAccount.ExpendBill.Sum(b => b.ExpendBillSpec.Sum(s => s.Summa));
                System.Diagnostics.Debug.WriteLine(string.Format("summm1={0}", summm1));
                var summm2 = consolidatedAccount.ExpendBill.Where(b => b.StateId == (int)StateEnum.ExpendBillExecuted).Sum(b => b.ExpendBillSpec.Sum(s => s.Summa));
                System.Diagnostics.Debug.WriteLine(string.Format("summm2={0}", summm2));
                var summm3 = entity.OrderOtgruzkaList.Sum(o => o.Summa);
                System.Diagnostics.Debug.WriteLine(string.Format("summm3={0}", summm3));
                var summm4 = entity.OrderOtgruzkaList.Sum(o => o.Orders.Sum(oo => oo.ItogoSumm));
                System.Diagnostics.Debug.WriteLine(string.Format("summm4={0}", summm4));
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                var itogoBillSummTemp = 0.0;
                foreach (var bill in consolidatedAccount.ExpendBill)
                {
                    System.Diagnostics.Debug.WriteLine("=========================================");
                    System.Diagnostics.Debug.WriteLine(string.Format("bill.ItogoSumm={0}   bill.State.Name={1}   bill.Id={2}   bill.Order.Number={3}", bill.ItogoSumm, bill.State.Name, bill.Id, bill.Order.Number));
                    var billSummTemp = 0.0;
                    foreach (var spec in bill.ExpendBillSpec)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("spec.Summa={0}   spec.ProductId={1}   spec.ProductName={2}   spec.Price={3}   spec.Count={4}", spec.Summa, spec.ProductId, spec.ProductName, spec.Price, spec.Count));
                        billSummTemp += spec.Summa;
                    }
                    itogoBillSummTemp += billSummTemp;
                    System.Diagnostics.Debug.WriteLine("-----------------------------------");
                    System.Diagnostics.Debug.WriteLine(string.Format("billSummTemp={0}", billSummTemp));
                    System.Diagnostics.Debug.WriteLine("=========================================");
                }
                System.Diagnostics.Debug.WriteLine(string.Format("itogoBillSummTemp={0}", itogoBillSummTemp));
                System.Diagnostics.Debug.WriteLine("=========================================");

                // Сортировка по Центрам затрат и потом по ID заказа
                entity.OrderOtgruzkaList = entity.OrderOtgruzkaList.OrderBy(o => o.CostsCenterName).ToList();
                entity.OrderOtgruzkaList.ForEach(i => i.Orders = i.Orders.OrderBy(o => o.Id).ToList());
            }

            if (consolidatedAccount.State != null)
                entity.State = consolidatedAccount.State;

            if (consolidatedAccount.ConsolidatedAccountSpec != null && consolidatedAccount.ConsolidatedAccountSpec.Count > 0)
                entity.Specification = consolidatedAccount.ConsolidatedAccountSpec.Select(s => EntityHelper.GetConsolidatedAccountSpecEntity2(s)).ToList();

            return entity;
        }


        /// <summary>
        /// Возвращает пользовательский класс ConsolidatedAccountInvoiceEntity по EntityFramework-объекту ConsolidatedAccount 
        /// </summary>
        /// <param name="consolidatedAccount"></param>
        /// <returns></returns>
        public static ConsolidatedAccountInvoiceEntity GetConsolidatedAccountInvoiceEntity(ConsolidatedAccount consolidatedAccount)
        {
            if (consolidatedAccount == null)
                return null;

            ConsolidatedAccountInvoiceEntity entity = new ConsolidatedAccountInvoiceEntity()
            {
                Id = consolidatedAccount.Id,
                CreatedDate = consolidatedAccount.CreatedDate,
                CreatedUserId = consolidatedAccount.CreatedUserId,
                Number = consolidatedAccount.Number,
                JuridicalPersonId = consolidatedAccount.JuridicalPersonId,
                PeriodDateStart = consolidatedAccount.PeriodDateStart,
                PeriodDateEnd = consolidatedAccount.PeriodDateEnd,
                StateId = consolidatedAccount.StateId
            };

            entity.JuridicalPerson = consolidatedAccount.JuridicalPerson;

            if (consolidatedAccount.State != null)
                entity.State = consolidatedAccount.State;

            if (consolidatedAccount.ConsolidatedAccountSpec != null && consolidatedAccount.ConsolidatedAccountSpec.Count > 0)
                entity.Specification = consolidatedAccount.ConsolidatedAccountSpec.Select(s => EntityHelper.GetConsolidatedAccountSpecEntity2(s)).ToList();

            return entity;
        }


        #region Блок методов для Справочников

        public static CostsCenterEntity GetCostsCenterEntity(CostsCenter costsCenter)
        {
            if (costsCenter == null)
                return null;

            CostsCenterEntity entity = new CostsCenterEntity();
            entity.CostsCenterId = costsCenter.CostsCenterId;
            entity.Name = costsCenter.Name;
            if (costsCenter.Department != null)
            {
                entity.DepartmentId = costsCenter.Department.DepartmentId;
                entity.DepartmentName = costsCenter.Department.Name;
            }

            return entity;
        }


        public static DepartmentEntity GetDepartmentEntity(Department department)
        {
            if (department == null)
                return null;

            DepartmentEntity entity = new DepartmentEntity();
            entity.DepartmentId = department.DepartmentId;
            entity.Name = department.Name;
            entity.OfficeNumber = department.OfficeNumber;

            if (department.JuridicalPerson != null)
            {
                entity.JuridicalPersonId = department.JuridicalPerson.JuridicalPersonId;
                entity.JuridicalPersonName = department.JuridicalPerson.Name;
            }

            return entity;
        }


        public static JuridicalPersonEntity GetJuridicalPersonEntity(JuridicalPerson juridicalPerson)
        {
            if (juridicalPerson == null)
                return null;

            JuridicalPersonEntity entity = new JuridicalPersonEntity();
            entity.JuridicalPersonId = juridicalPerson.JuridicalPersonId;
            entity.Name = juridicalPerson.Name;
            entity.ManagerEMail = juridicalPerson.ManagerEMail;

            if (juridicalPerson.Company != null)
            {
                entity.CompanyId = juridicalPerson.Company.CompanyId;
                entity.CompanyName = juridicalPerson.Company.CompanyName;
            }

            return entity;
        }


        public static CostsCenterFullInfoEntity GetCostsCenterFullInfoEntity(CostsCenter costsCenter)
        {
            if (costsCenter == null)
                return null;

            CostsCenterFullInfoEntity entity = new CostsCenterFullInfoEntity();
            entity.CostsCenterId = costsCenter.CostsCenterId;
            entity.Name = costsCenter.Name;
            entity.BS = costsCenter.BS;
            entity.MVZ = costsCenter.MVZ;
            if (costsCenter.Department != null)
            {
                entity.DepartmentId = costsCenter.Department.DepartmentId;
                entity.DepartmentName = costsCenter.Department.Name;
            }
            if (costsCenter.User != null && costsCenter.User.Count > 0)
            {
                var user = costsCenter.User.FirstOrDefault();
                if (user != null)
                {
                    entity.UserFIO = user.FIO;
                    entity.UserId = user.UserId;
                    entity.UserEmail = user.Email;
                    entity.UserIsEnable = user.IsEnable;
                    entity.UserLogin = user.Login;
                    entity.UserPassHash = user.PassHash;
                    entity.UserPhone = user.Phone;
                    entity.UserRole = EntityHelper.GetRoleEntity(user.Role);
                }
            }

            return entity;
        }


        #endregion Блок методов для Справочников


        public static ProductEntity GetProductEntity(Product product)
        {
            if (product == null)
                return null;

            ProductEntity entity = new ProductEntity();
            entity.Product = product;
            entity.MeasureUnit = product.MeasureUnit;

            return entity;
        }

    }
}
